<template>
  <div class="left-side">
    <div class="left-side-inner">
      <ul class="menu-box">
          <!-- 2级路由点击在lev2Click处理 -->
          <router-link 
          v-for="(cnav, index) in nav[currentNavGroupIndex].children"
          :to="cnav.path" 
          tag="li"
          :key="index"
          class="menu-item"
          :class="lev2Class(cnav,index)"
          event=""
          > 
            <span @click.stop="lev2Click(cnav, $event,index)">{{cnav.title}}</span>
            <ul v-if="cnav.children">
              <router-link
                v-for="(child, cIndex) in cnav.children"
                :to="child.path" 
                tag="li"
                :key="cIndex"
                class="sub-menu-item"
              >
                <span>{{child.title}}</span>
              </router-link>
            </ul>
          </router-link>
      </ul>
    </div>
  </div>
</template>
<script type="text/javascript">
  import classnames from 'classnames'
  export default {
    name: 'slide',
    data(){
      return {
        currentNavGroupIndex:-1,
        openKey:[]
      }
    },
    created(){
      this.getCurrentNavGroup();
    },
    mounted() {
    },
    watch: {
    '$route' (val, old) {
        this.getCurrentNavGroup();
      }
    },
    props:['nav'],
    methods:{
      getCurrentNavGroup(){
        let segmentArr = this.$route.path.split('/');
        let lev1Path='/'+segmentArr[1];
        let lev2Path='/'+segmentArr[1] + '/' + segmentArr[2]
        for(let i=0;i<this.nav.length;i++){
          if(this.nav[i].path == lev1Path){
            if(this.currentNavGroupIndex!=i){
              this.currentNavGroupIndex=i;
              for(var j=0;j<this.nav[i].children.length;j++){
                if(this.nav[i].children[j].path == lev2Path){
                  this.openKey = [ j];
                }
              }
            }
 
          }
        }
      },
      lev2Click(nav,event,index){
        if(nav.children){
          let openKeyIndex=this.openKey.indexOf(index);
          if(openKeyIndex > -1){
            this.openKey.splice(openKeyIndex, 1); 

          }else{
            this.openKey.push(index);
          }
        }else{
          this.$router.push(nav.path);
        }
      },
      lev2Class(nav,index){
        let hasChildren = !!nav.children;
        let open = false;
        for(let i=0 ;i < this.openKey.length; i++){
          if(this.openKey[i] == index){
            open=true;
            break;
          }
        }
        return classnames(nav.icon,{
          hasChildren,
          open
        });
      }
    },
  }
</script>
